package com.platform.comm.validation;

import com.platform.comm.validation.constraints.EqualField;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

/**
 * 功能描述: 验证字段相等实现
 *
 * @author tommy create on 2018-03-14-13:34
 */
public class EqualFieldValidator implements ConstraintValidator<EqualField,Object> {
    private String baseField;
    private String matchField;

    @Override
    public void initialize(EqualField constraint) {
        baseField  = constraint.baseField();
        matchField = constraint.matchField();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        try {
            Object baseFieldValue = getFieldValue(object,baseField);
            Object matchFieldValue = getFieldValue(object,matchField);

            return baseFieldValue != null && baseFieldValue.equals(matchFieldValue);
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 通过反射获取字段值
     * @param object 目标类
     * @param fieldName 字段名
     * @return Object
     * @throws Exception 异常
     */
    private Object getFieldValue(Object object, String fieldName) throws Exception {
        Class<?> clazz = object.getClass();
        Field sField = clazz.getDeclaredField(fieldName);
        sField.setAccessible(true);

        return sField.get(object);
    }

}
